package com.example.zhang;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ListActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;

import androidx.annotation.NonNull;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

public class MylistActivity extends ListActivity implements Runnable {

    private static final String TAG ="a" ;
    String name;
    float data;
    Handler handler;
    ArrayList<String> sites_test = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_mylist);
        Thread t = new Thread((Runnable) this);//开启后会启动子线程中的run方法.
        t.start();

        handler = new Handler(){
            @SuppressLint("HandlerLeak")
            @Override
            public void handleMessage(@NonNull Message msg){
                if(msg.what==1){
                    ArrayList<String> sites = (ArrayList<String>)msg.obj;
                    ListAdapter adapter = new ArrayAdapter<String>(MylistActivity.this, android.R.layout.simple_list_item_1,sites);
                    setListAdapter(adapter);
                }
                super.handleMessage(msg);
            }
        };
    }

    @Override
    public void run(){
        try {
            Document doc = Jsoup.connect("http://www.usd-cny.com/bankofchina.htm").get();
            Elements pros = doc.getElementsByTag("tr");
                for (Element pro : pros) {
                    Elements data1 = pro.getElementsByTag("td");
                    if (data1.size() > 0 && !data1.get(1).text().equals("-")) {
                        name = data1.get(0).text();
                        data = Float.parseFloat(data1.get(1).text());
                        sites_test.add(name+"----"+data);
                        Log.i(TAG, "......." + name + "...." + data);
                    }
                }
            }

        catch(IOException e){
            e.printStackTrace();
        }
        Message msg1 = handler.obtainMessage(1);
        msg1.obj =sites_test;
        handler.sendMessage(msg1);

    }

}